import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'dart:io';

import '../../controllers/record_detail_controller.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_text_styles.dart';
import '../../core/constants/app_constants.dart';
import '../../core/constants/emotion_constants.dart';
import '../../core/utils/app_utils.dart';


/// 记录详情页面 - 用于查看和编辑情绪记录详情
/// Record Detail Page - For viewing and editing emotion record details
class RecordDetailPage extends GetView<RecordDetailController> {
  const RecordDetailPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('记录详情'),
        actions: [
          // 编辑按钮 / Edit button
          Obx(() => IconButton(
            icon: Icon(
              controller.isEditing.value ? Icons.close : Icons.edit,
              color: AppColors.primary,
            ),
            onPressed: controller.toggleEdit,
          )),
          
          // 删除按钮 / Delete button
          Obx(() => !controller.isEditing.value
            ? IconButton(
                icon: const Icon(
                  Icons.delete,
                  color: AppColors.error,
                ),
                onPressed: () => _showDeleteDialog(context),
              )
            : Container()),
          
          // 保存按钮 / Save button
          Obx(() => controller.isEditing.value
            ? IconButton(
                icon: const Icon(
                  Icons.save,
                  color: AppColors.success,
                ),
                onPressed: controller.saveChanges,
              )
            : Container()),
        ],
      ),
      body: Obx(() => controller.isLoading.value
          ? const Center(child: CircularProgressIndicator())
          : _buildRecordDetail(context)),
    );
  }

  /// 构建记录详情内容
  /// Build record detail content
  Widget _buildRecordDetail(BuildContext context) {
    final record = controller.record.value;
    if (record == null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.error_outline,
              size: 64,
              color: AppColors.textSecondary,
            ),
            const SizedBox(height: AppConstants.spacingMedium),
            Text(
              '记录不存在',
              style: AppTextStyles.titleMedium.copyWith(
                color: AppColors.textSecondary,
              ),
            ),
          ],
        ),
      );
    }

    return SingleChildScrollView(
      padding: EdgeInsets.all(16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 记录时间 / Record time
          _buildTimeSection(record.createdAt),
          SizedBox(height: 24.h),
          
          // 情绪信息 / Emotion information
          _buildEmotionSection(record.emotionType.value, record.emotionIntensity),
          SizedBox(height: 24.h),
          
          // 日记内容 / Diary content
          if (record.diaryContent != null && record.diaryContent!.isNotEmpty) ...[
            _buildDiarySection(record.diaryContent!),
            const SizedBox(height: AppConstants.spacingLarge),
          ],
          
          // 媒体文件 / Media files
          if ((record.imagePaths?.isNotEmpty ?? false) || (record.audioPath?.isNotEmpty ?? false)) ...[
            _buildMediaSection(record.imagePaths ?? [], record.audioPath ?? ''),
            const SizedBox(height: AppConstants.spacingLarge),
          ],
          
          // 标签 / Tags
          if (record.tags?.isNotEmpty ?? false) ...[
            _buildTagsSection(record.tags ?? []),
            const SizedBox(height: AppConstants.spacingLarge),
          ],
          
          // 统计信息 / Statistics
          _buildStatsSection(context, record),
        ],
      ),
    );
  }

  /// 构建时间区域
  /// Build time section
  Widget _buildTimeSection(DateTime createdAt) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            AppColors.primary.withOpacity(0.1),
            AppColors.secondary.withOpacity(0.1),
          ],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(color: AppColors.primary.withOpacity(0.2)),
      ),
      child: Column(
        children: [
          Icon(
            Icons.access_time,
            color: AppColors.primary,
            size: 24.w,
          ),
          SizedBox(height: 8.h),
          Text(
            AppUtils.formatDateTime(createdAt),
            style: AppTextStyles.titleMedium.copyWith(
              color: AppColors.primary,
            ),
          ),
          Text(
            AppUtils.getRelativeTime(createdAt),
            style: AppTextStyles.bodySmall.copyWith(
              color: AppColors.textSecondary,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建情绪区域
  /// Build emotion section
  Widget _buildEmotionSection(String emotionType, int intensity) {
    final emotionColor = EmotionConstants.getEmotionColor(emotionType);
    final emotionEmoji = EmotionConstants.getEmotionEmoji(emotionType);
    final emotionLabel = EmotionConstants.getEmotionLabel(emotionType);
    final intensityLabel = EmotionConstants.getIntensityLabel(intensity);

    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: AppConstants.shadowSoft,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '情绪状态',
            style: AppTextStyles.titleMedium.copyWith(
              color: AppColors.textPrimary,
            ),
          ),
          const SizedBox(height: AppConstants.spacingMedium),
          
          Row(
            children: [
              // 情绪图标和标签 / Emotion icon and label
              Container(
                padding: const EdgeInsets.all(AppConstants.paddingMedium),
                decoration: BoxDecoration(
                  color: emotionColor.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
                  border: Border.all(color: emotionColor.withOpacity(0.3)),
                ),
                child: Column(
                  children: [
                    Text(
                      emotionEmoji,
                      style: const TextStyle(fontSize: 32),
                    ),
                    const SizedBox(height: AppConstants.spacingSmall),
                    Text(
                      emotionLabel,
                      style: AppTextStyles.bodyMedium.copyWith(
                        color: emotionColor,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ],
                ),
              ),
              
              const SizedBox(width: AppConstants.spacingLarge),
              
              // 强度信息 / Intensity information
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '强度等级',
                      style: AppTextStyles.bodyMedium.copyWith(
                        color: AppColors.textSecondary,
                      ),
                    ),
                    const SizedBox(height: AppConstants.spacingSmall),
                    
                    // 强度条 / Intensity bar
                    Container(
                      height: 8,
                      decoration: BoxDecoration(
                        color: AppColors.border,
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: FractionallySizedBox(
                        alignment: Alignment.centerLeft,
                        widthFactor: intensity / 10.0,
                        child: Container(
                          decoration: BoxDecoration(
                            color: emotionColor,
                            borderRadius: BorderRadius.circular(4),
                          ),
                        ),
                      ),
                    ),
                    
                    const SizedBox(height: AppConstants.spacingSmall),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          '$intensity/10',
                          style: AppTextStyles.titleSmall.copyWith(
                            color: emotionColor,
                          ),
                        ),
                        Text(
                          intensityLabel,
                          style: AppTextStyles.bodySmall.copyWith(
                            color: AppColors.textSecondary,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建日记区域
  /// Build diary section
  Widget _buildDiarySection(String content) {
    return Container(
      padding: const EdgeInsets.all(AppConstants.paddingMedium),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(AppConstants.radiusMedium),
        boxShadow: AppConstants.shadowSoft,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                Icons.book,
                color: AppColors.primary,
                size: AppConstants.iconSizeSmall,
              ),
              const SizedBox(width: AppConstants.spacingSmall),
              Text(
                '日记内容',
                style: AppTextStyles.titleMedium.copyWith(
                  color: AppColors.textPrimary,
                ),
              ),
            ],
          ),
          const SizedBox(height: AppConstants.spacingMedium),
          
          Obx(() => controller.isEditing.value
              ? TextField(
                  controller: controller.contentController,
                  maxLines: null,
                  decoration: InputDecoration(
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
                      borderSide: BorderSide(color: AppColors.border),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
                      borderSide: BorderSide(color: AppColors.border),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
                      borderSide: BorderSide(color: AppColors.primary, width: 2),
                    ),
                    filled: true,
                    fillColor: AppColors.background,
                  ),
                  style: AppTextStyles.bodyMedium,
                )
              : Container(
                  width: double.infinity,
                  padding: const EdgeInsets.all(AppConstants.paddingMedium),
                  decoration: BoxDecoration(
                    color: AppColors.background,
                    borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
                    border: Border.all(color: AppColors.border),
                  ),
                  child: Text(
                    content,
                    style: AppTextStyles.bodyMedium.copyWith(
                      height: 1.6,
                    ),
                  ),
                ),
          ),
        ],
      ),
    );
  }

  /// 构建媒体区域
  /// Build media section
  Widget _buildMediaSection(List<String> imagePaths, String audioPath) {
    return Container(
      padding: const EdgeInsets.all(AppConstants.paddingMedium),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(AppConstants.radiusMedium),
        boxShadow: AppConstants.shadowSoft,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                Icons.perm_media,
                color: AppColors.primary,
                size: AppConstants.iconSizeSmall,
              ),
              const SizedBox(width: AppConstants.spacingSmall),
              Text(
                '媒体文件',
                style: AppTextStyles.titleMedium.copyWith(
                  color: AppColors.textPrimary,
                ),
              ),
            ],
          ),
          const SizedBox(height: AppConstants.spacingMedium),
          
          // 图片列表 / Image list
          if (imagePaths.isNotEmpty) ...[
            Text(
              '图片 (${imagePaths.length})',
              style: AppTextStyles.bodyMedium.copyWith(
                color: AppColors.textSecondary,
              ),
            ),
            const SizedBox(height: AppConstants.spacingSmall),
            SizedBox(
              height: 120,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: imagePaths.length,
                itemBuilder: (context, index) {
                  final imagePath = imagePaths[index];
                  return Container(
                    margin: const EdgeInsets.only(right: AppConstants.spacingMedium),
                    child: GestureDetector(
                      onTap: () => _showImageDialog(context, imagePath),
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
                        child: Image.file(
                          File(imagePath),
                          width: 120,
                          height: 120,
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),
          ],
          
          // 录音文件 / Audio file
          if (audioPath.isNotEmpty) ...[
            if (imagePaths.isNotEmpty) 
              const SizedBox(height: AppConstants.spacingMedium),
            Text(
              '录音文件',
              style: AppTextStyles.bodyMedium.copyWith(
                color: AppColors.textSecondary,
              ),
            ),
            const SizedBox(height: AppConstants.spacingSmall),
            Container(
              padding: const EdgeInsets.all(AppConstants.paddingMedium),
              decoration: BoxDecoration(
                color: AppColors.background,
                borderRadius: BorderRadius.circular(AppConstants.radiusSmall),
                border: Border.all(color: AppColors.border),
              ),
              child: Row(
                children: [
                  Icon(
                    Icons.audiotrack,
                    color: AppColors.primary,
                    size: AppConstants.iconSizeSmall,
                  ),
                  const SizedBox(width: AppConstants.spacingSmall),
                  Expanded(
                    child: Text(
                      '录音文件.m4a',
                      style: AppTextStyles.bodyMedium,
                    ),
                  ),
                  Obx(() => IconButton(
                    onPressed: controller.isPlaying.value 
                        ? controller.stopAudio 
                        : () => controller.playAudio(audioPath),
                    icon: Icon(
                      controller.isPlaying.value ? Icons.stop : Icons.play_arrow,
                      color: AppColors.primary,
                    ),
                  )),
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }

  /// 构建标签区域
  /// Build tags section
  Widget _buildTagsSection(List<String> tags) {
    return Container(
      padding: const EdgeInsets.all(AppConstants.paddingMedium),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(AppConstants.radiusMedium),
        boxShadow: AppConstants.shadowSoft,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                Icons.local_offer,
                color: AppColors.primary,
                size: AppConstants.iconSizeSmall,
              ),
              const SizedBox(width: AppConstants.spacingSmall),
              Text(
                '标签',
                style: AppTextStyles.titleMedium.copyWith(
                  color: AppColors.textPrimary,
                ),
              ),
            ],
          ),
          const SizedBox(height: AppConstants.spacingMedium),
          
          Wrap(
            spacing: AppConstants.spacingSmall,
            runSpacing: AppConstants.spacingSmall,
            children: tags.map((tag) {
              return Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: AppConstants.paddingMedium,
                  vertical: AppConstants.paddingSmall,
                ),
                decoration: BoxDecoration(
                  color: AppColors.primary.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(AppConstants.radiusLarge),
                  border: Border.all(color: AppColors.primary.withOpacity(0.3)),
                ),
                child: Text(
                  tag,
                  style: AppTextStyles.bodySmall.copyWith(
                    color: AppColors.primary,
                  ),
                ),
              );
            }).toList(),
          ),
        ],
      ),
    );
  }

  /// 构建统计区域
  /// Build statistics section
  Widget _buildStatsSection(BuildContext context, dynamic record) {
    return Container(
      padding: const EdgeInsets.all(AppConstants.paddingMedium),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(AppConstants.radiusMedium),
        boxShadow: AppConstants.shadowSoft,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                Icons.analytics,
                color: AppColors.primary,
                size: AppConstants.iconSizeSmall,
              ),
              const SizedBox(width: AppConstants.spacingSmall),
              Text(
                '记录信息',
                style: AppTextStyles.titleMedium.copyWith(
                  color: AppColors.textPrimary,
                ),
              ),
            ],
          ),
          const SizedBox(height: AppConstants.spacingMedium),
          
          // 使用Wrap替代Row来避免溢出问题
          // Use Wrap instead of Row to avoid overflow issues
          Wrap(
            spacing: AppConstants.spacingMedium,
            runSpacing: AppConstants.spacingMedium,
            children: [
              SizedBox(
                width: (MediaQuery.of(context).size.width - 64) / 2 - AppConstants.spacingMedium / 2,
                child: _buildStatItem(
                  icon: Icons.text_fields,
                  label: '字数',
                  value: '${record.diaryContent?.length ?? 0}',
                ),
              ),
              SizedBox(
                width: (MediaQuery.of(context).size.width - 64) / 2 - AppConstants.spacingMedium / 2,
                child: _buildStatItem(
                  icon: Icons.image,
                  label: '图片',
                  value: '${record.imagePaths?.length ?? 0}',
                ),
              ),
              SizedBox(
                width: (MediaQuery.of(context).size.width - 64) / 2 - AppConstants.spacingMedium / 2,
                child: _buildStatItem(
                  icon: Icons.audiotrack,
                  label: '录音',
                  value: (record.audioPath?.isNotEmpty ?? false) ? '1' : '0',
                ),
              ),
              SizedBox(
                width: (MediaQuery.of(context).size.width - 64) / 2 - AppConstants.spacingMedium / 2,
                child: _buildStatItem(
                  icon: Icons.local_offer,
                  label: '标签',
                  value: '${record.tags?.length ?? 0}',
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建统计项
  /// Build stat item
  Widget _buildStatItem({
    required IconData icon,
    required String label,
    required String value,
  }) {
    return Column(
      children: [
        Icon(
          icon,
          color: AppColors.primary,
          size: AppConstants.iconSizeSmall,
        ),
        const SizedBox(height: AppConstants.spacingSmall),
        Text(
          value,
          style: AppTextStyles.titleMedium.copyWith(
            color: AppColors.primary,
          ),
        ),
        Text(
          label,
          style: AppTextStyles.bodySmall.copyWith(
            color: AppColors.textSecondary,
          ),
        ),
      ],
    );
  }

  /// 显示图片对话框
  /// Show image dialog
  void _showImageDialog(BuildContext context, String imagePath) {
    showDialog(
      context: context,
      builder: (context) => Dialog(
        backgroundColor: Colors.transparent,
        child: GestureDetector(
          onTap: () => Navigator.of(context).pop(),
          child: Container(
            constraints: BoxConstraints(
              maxHeight: MediaQuery.of(context).size.height * 0.8,
              maxWidth: MediaQuery.of(context).size.width * 0.9,
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(AppConstants.radiusMedium),
              child: Image.file(
                File(imagePath),
                fit: BoxFit.contain,
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 显示删除对话框
  /// Show delete dialog
  void _showDeleteDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(
          '删除记录',
          style: AppTextStyles.titleMedium,
        ),
        content: Text(
          '确定要删除这条记录吗？此操作无法撤销。',
          style: AppTextStyles.bodyMedium,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text(
              '取消',
              style: AppTextStyles.button.copyWith(
                color: AppColors.textSecondary,
              ),
            ),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              controller.deleteRecord();
            },
            child: Text(
              '删除',
              style: AppTextStyles.button.copyWith(
                color: AppColors.error,
              ),
            ),
          ),
        ],
      ),
    );
  }
}